package form

import (
	"gitee.com/zjlsliupei/ghelp"
	"gitee.com/zjlsliupei/ndb/config"
	"gitee.com/zjlsliupei/ndb/request"
	"github.com/gin-gonic/gin"
	"github.com/tidwall/gjson"
)

type FormList struct {
	option     config.Option
	rpcName    string
	funcName   string
	arg        ghelp.MAP
	meta       ghelp.MAP
	ginContext *gin.Context
}

func NewFormList(option config.Option, rpcName string) FormList {
	return FormList{
		option:   option,
		rpcName:  rpcName,
		funcName: "FormList",
		arg:      make(ghelp.MAP),
	}
}

// SetGroupId 不超过20位，用于数据分组
func (this *FormList) SetGroupId(groupId string) *FormList {
	this.arg["group_id"] = groupId
	return this
}

// SetAppId 所属app的id
func (this *FormList) SetAppId(appId string) *FormList {
	this.arg["app_id"] = appId
	return this
}

// SetFormClass 表单分类，用于表单分组, 必填
func (this *FormList) SetFormClass(formClass []interface{}) *FormList {
	this.arg["form_class"] = formClass
	return this
}

// SetState 状态，默认不限制
func (this *FormList) SetState(state []int64) *FormList {
	this.arg["state"] = state
	return this
}

// SetSize 默认15
func (this *FormList) SetSize(size int64) *FormList {
	this.arg["size"] = size
	return this
}

// SetPage 从1开始
func (this *FormList) SetPage(page int64) *FormList {
	this.arg["page"] = page
	return this
}

// AutoMeta 自动设置meta，根据gin的上下文来解析，meta; 如果同时使用了Meta优先以Meta为准
func (this *FormList) AutoMeta(c *gin.Context) *FormList {
	_c := c.Copy()
	this.ginContext = _c
	return this
}

// SetMeta 设置meta
func (this *FormList) SetMeta(meta ghelp.MAP) *FormList {
	this.meta = meta
	return this
}

func (this *FormList) Do() (gjson.Result, error) {
	req := request.NewRequest(this.option.Addr)
	req.FuncName(this.funcName)
	req.RpcName(this.rpcName)
	req.AutoMeta(this.ginContext)
	req.SetMeta(this.meta)
	return req.Do(this.arg)
}
